package com.projects.xenia.journals_activities;

import android.app.ListActivity;
import android.content.Intent;

	


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.projects.xenia.GPSLocationActivity;
import com.projects.xenia.MainCustomersListActivity;
import com.projects.xenia.R;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.ref_classes.CustomersRefItem;
import com.projects.xenia.ref_classes.CustomersRefObject;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;

import android.database.Cursor;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public abstract class JournalActivity extends ListActivity {

		private EfficientAdapter adap;
		
		public String id;
		
		private int docnum;
		private String date_create;
		private int state;
		private String customres_id;
		private Double totalorder_sum;
		private String descr;
		private String outletdescr;
		private String outletadress; 
		private String outlettelephone;
		private Double total_sum;
		
		private Button JournalStartDate;
		private Button JournalStopDate;
		
		
		private final int IDR_CustomerSelect = 0;
		
		private final int IDD_JournalStartDateDateDialog = 0;
		private final int IDD_JournalStopDateDateDialog = 1;
		private final int IDD_ActionsAlertDialog = 2;
		
		private ImageView doc_add;
		private ImageView r_first;
		private ImageView _BackWardButton;
		private ImageView customer_back;
		
		public Context Ctx;
		
		public Cursor JournalCursor;
		
		public TextView head_text;
		public ImageView head_ico;		
		
		public Button Journ_Customer;	
		public TextView JournalTotalSum;
		public Date JournalStartDateValue;
		public Date JournalStopDateValue;
		
		public void onActivityResultFromChild (int requestCode, int resultCode, Intent data) {
			
			if (requestCode==IDR_CustomerSelect && data!=null ) {
				String customer_id = data.getStringExtra("customer_id");
				CustomersRefObject _CustomersRefObject = new CustomersRefObject ();			
				if (customer_id!=null && _CustomersRefObject.GetCustomerById(customer_id)) {
					Journ_Customer.setText(_CustomersRefObject.GetCustomersDescrLong());
					Journ_Customer.setTag(_CustomersRefObject.RefItem.id);
				}
			}			
			RefreshList();
			SetButtonsVisibility ();
		}

		public Activity getActivityContext() {
		
		    if (getParent() instanceof TabActivity) {	
		        return getParent();	
		    } 
		    else 
		    {
		    	return this;	
		    }
		}

		
		private void RefreshDate (Button DateButton,Date DateValue) {			
			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
			DateButton.setText(sdf.format(DateValue));			
		}	
		
		
		
		public abstract void JournIcoEvents ();
		
		public abstract void GetJournalCursor ();
		
		public abstract void SetIconAndDescr ();
		
		@Override
		public void onCreate(Bundle savedInstanceState) {
			
			super.onCreate(savedInstanceState);
			
	        requestWindowFeature(Window.FEATURE_NO_TITLE);            
	        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
			setContentView(R.layout.journal_form);
			
			Ctx = getActivityContext();
			
			_BackWardButton = (ImageView)findViewById(R.id.cust_backward);
			_BackWardButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					finish();
				}
			});
			
			Calendar C = Calendar.getInstance();
			JournalStartDateValue = C.getTime();
			JournalStopDateValue = C.getTime();
			
			JournalStartDate = (Button)findViewById(R.id.JournalStartDate);
			JournalStartDate.setOnClickListener(JournalStartDateDateDialog);
			RefreshDate (JournalStartDate,JournalStartDateValue);
			
			JournalStopDate = (Button)findViewById(R.id.JournalStopDate);
			JournalStopDate.setOnClickListener(JournalStopDateDateDialog);
			RefreshDate (JournalStopDate,JournalStopDateValue); 
			
			JournalTotalSum = (TextView)findViewById(R.id.JournalTotalSum);
			
			customer_back= (ImageView)findViewById(R.id.customer_back);
			customer_back.setOnClickListener(new OnClickListener() {			
				@Override
				public void onClick(View v) {
					Journ_Customer.setText("");
					Journ_Customer.setTag(null);
					RefreshList ();
				}
			});
			
			Journ_Customer = (Button)findViewById(R.id.Journ_Customer);
			Journ_Customer.setOnClickListener(new OnClickListener() {			
				@Override
				public void onClick(View v) {
					CustomerSelect();
				}
			});
			
			Bundle DocExtra = getIntent().getExtras();
			
			if (DocExtra!=null) {
				String customer_id = DocExtra.getString("customer_id");
				CustomersRefObject _CustomersRefObject = new CustomersRefObject ();			
				if (customer_id!=null && _CustomersRefObject.GetCustomerById(customer_id)) {
					Journ_Customer.setText(_CustomersRefObject.GetCustomersDescrLong());
					Journ_Customer.setTag(_CustomersRefObject.RefItem.id);
				}
			}
			
			
			head_text = (TextView)findViewById(R.id.journ_text);
			head_ico = (ImageView)findViewById(R.id.journ_ico);
			SetIconAndDescr();
			
			head_ico = (ImageView)findViewById(R.id.journ_ico);
			head_ico.setOnClickListener(new OnClickListener() {				
				@Override
				public void onClick(View v) {
					JournIcoEvents ();					
				}
			});
			
			GetJournalCursor ();
			
			adap = new EfficientAdapter(Ctx);
			setListAdapter(adap);
		
			r_first = (ImageView)findViewById(R.id.r_first);
			
			doc_add = (ImageView)findViewById(R.id.doc_add);
			doc_add.setOnClickListener(new OnClickListener() {			
				@Override
				public void onClick(View v) {
					
					CreateOpenDocument ();
				}
			});
			
			getListView().setOnItemClickListener(onListItemClick);
			
			MainGlobalModule.setBackGround(getListView());
			
			SetButtonsVisibility ();
			 
		}
		
		
		private void SetButtonsVisibility () {
			
			if (MainGlobalModule.CheckLocationToday(true)) {
				r_first.setVisibility(View.GONE);
				doc_add.setVisibility(View.VISIBLE);
			}
			else {
				r_first.setVisibility(View.VISIBLE);
				doc_add.setVisibility(View.GONE);
			}
			
		}
		
		
		private void CustomerSelect () {
			
			Intent CustomerSelectintent = new Intent();		
			CustomerSelectintent.setClass(Ctx,MainCustomersListActivity.class);
			CustomerSelectintent.putExtra("customer_id",String.valueOf(Journ_Customer.getTag()));		
			((Activity) Ctx).startActivityForResult (CustomerSelectintent,IDR_CustomerSelect);
			
		}

		public abstract void StartDocumentsDetailsJournalActivity ();
		
		private OnItemClickListener onListItemClick = new OnItemClickListener() {@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
			
				adap.getItem(position);
				showDialog(IDD_ActionsAlertDialog);
				
			}
			
		};	
		
		private OnClickListener JournalStartDateDateDialog = new OnClickListener() {		
			@Override
			public void onClick(View v) {
				showDialog(IDD_JournalStartDateDateDialog);			
			}
		};

		private OnClickListener JournalStopDateDateDialog = new OnClickListener() {		
			@Override
			public void onClick(View v) {
				showDialog(IDD_JournalStopDateDateDialog);			
			}
		};			
		
		private OnDateSetListener JournalStartDateDateSetListener = new OnDateSetListener() {		
			@Override
			public void onDateSet(DatePicker view, int year, int month,int day) {						
				Calendar C = Calendar.getInstance();
				C.set(year, month, day);
				JournalStartDateValue = C.getTime();
				RefreshDate (JournalStartDate,JournalStartDateValue);
				RefreshList ();
				Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				vb.vibrate(30);
			}
		};

		private OnDateSetListener JournalStopDateDateSetListener = new OnDateSetListener() {		
			@Override
			public void onDateSet(DatePicker view, int year, int month,int day) {						
				Calendar C = Calendar.getInstance();
				C.set(year, month, day);			
				JournalStopDateValue = C.getTime();
				RefreshDate (JournalStopDate,JournalStopDateValue);
				RefreshList ();
				Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				vb.vibrate(30);
			}
		};
		
		@Override
		protected Dialog onCreateDialog(int id) {
			super.onCreateDialog(id);
			
			int mYear;
			int mMonth;
			int mDay;		
			Calendar C = Calendar.getInstance();		
			AlertDialog.Builder adb = new AlertDialog.Builder(getActivityContext());
			
			switch (id) {
			
				case IDD_JournalStartDateDateDialog:
					
				C.setTime(JournalStartDateValue);			
				mYear = C.get(Calendar.YEAR);
				mMonth = C.get(Calendar.MONTH);
				mDay = C.get(Calendar.DAY_OF_MONTH);			
				return new DatePickerDialog(Ctx, JournalStartDateDateSetListener, mYear, mMonth, mDay);
				
				case IDD_JournalStopDateDateDialog:
				
				C.setTime(JournalStopDateValue);			
				mYear = C.get(Calendar.YEAR);
				mMonth = C.get(Calendar.MONTH);
				mDay = C.get(Calendar.DAY_OF_MONTH);			
				return new DatePickerDialog(Ctx, JournalStopDateDateSetListener, mYear, mMonth, mDay);
			
				case IDD_ActionsAlertDialog:
				
				adb.setItems(new String [] {"Открыть","Удалить","Инфо"} ,ActionSelectDialogListener);		
				return adb.create();
			
				}
			
			return null;
			
		}
		
		@Override
		protected void onPrepareDialog(int id, Dialog dialog) {
			super.onPrepareDialog(id, dialog);
			
			int mYear;
			int mMonth;
			int mDay;
			Calendar C = Calendar.getInstance();
			DatePickerDialog M;
			
			switch (id) {
			
			case IDD_JournalStartDateDateDialog:		
				M = (DatePickerDialog)dialog;						
				C.setTime(JournalStartDateValue);		
				mYear = C.get(Calendar.YEAR);
				mMonth = C.get(Calendar.MONTH);
				mDay = C.get(Calendar.DAY_OF_MONTH);						
				M.updateDate(mYear, mMonth, mDay);
				break;
			case IDD_JournalStopDateDateDialog:		
				M = (DatePickerDialog)dialog;
				C.setTime(JournalStopDateValue);		
				mYear = C.get(Calendar.YEAR);
				mMonth = C.get(Calendar.MONTH);
				mDay = C.get(Calendar.DAY_OF_MONTH);						
				M.updateDate(mYear, mMonth, mDay);
				break;
			}
			
		}
		
				    
		public abstract void CreateOpenDocument ();	    
		public abstract void OpenDocument ();
		public abstract void DeleteDocument (); 
  
		
	    public void RefreshList () {
	    	GetJournalCursor ();
			adap.notifyDataSetChanged();
	    }	
	    
	    @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    	super.onActivityResult(requestCode, resultCode, data);
	    	onActivityResultFromChild (requestCode, resultCode, data);		    	
		};
	    
		private DialogInterface.OnClickListener ActionSelectDialogListener = new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int which) {
		    
		    	switch (which) {	    		
	    		case 0:
					OpenDocument ();
					break;
	    		case 1:
	    			DeleteDocument ();
	    			RefreshList ();
					break;
	    		case 2:
	    			StartDocumentsDetailsJournalActivity ();
	    			break;
		    	}
		  }		
		};
		
		public class EfficientAdapter extends BaseAdapter  {
		
			private LayoutInflater mInflater;
			public Context context;
			 
			public EfficientAdapter(Context context) { 
				mInflater = LayoutInflater.from(context);			
			}
			 
			public View getView(final int position, View convertView, ViewGroup parent) {

				ViewHolder holder;
			
				if (convertView == null) {
				
					convertView = mInflater.inflate(R.layout.journal_form_list, null);
			
					holder = new ViewHolder();				
					
					holder.Journal_Status = (ImageView) convertView.findViewById(R.id.Journal_State);					
					holder.Journal_Date = (TextView) convertView.findViewById(R.id.Journal_Date);
					holder.Journal_Num = (TextView) convertView.findViewById(R.id.Journal_Num);
					holder.Journal_CustomerDescr = (TextView) convertView.findViewById(R.id.Journal_CustomersDescr);
					holder.Journal_CustomerDetails = (TextView) convertView.findViewById(R.id.Journal_CustomersDetails);			
					holder.Journal_Sum = (TextView) convertView.findViewById(R.id.Journal_Sum);
					holder.Journal_AddSum = (TextView) convertView.findViewById(R.id.Journal_AddSum);
							
					convertView.setTag(holder);
			
			}
			
			else
				
				{
					holder = (ViewHolder) convertView.getTag();
				}
			
				getItem(position);
			
				
				switch (state) {
				
				case 1:
					{holder.Journal_Status.setImageResource(R.drawable.ic_newdoc);}			
					break;
					
				case 3:
					{holder.Journal_Status.setImageResource(R.drawable.ic_deldoc);}				
					break;
					
				case 7:
					{holder.Journal_Status.setImageResource(R.drawable.ic_deldoc);}				
					break;
					
				case 15:
					{holder.Journal_Status.setImageResource(R.drawable.ic_deldoc);}				
				break;
					
				case 5:
					{holder.Journal_Status.setImageResource(R.drawable.ic_sendeddoc);}
				break;
				
				case 13:
					{holder.Journal_Status.setImageResource(R.drawable.ic_bounddoc);}
					break;
					
				case 29:
					{holder.Journal_Status.setImageResource(R.drawable.ic_invoicedoc);}
					break;
					
				default:
					break;
				}
				
				holder.Journal_Date.setText(date_create);		
				holder.Journal_Num.setText(String.format("№%d / %d",docnum,state));
				holder.Journal_CustomerDescr.setText(descr);
				holder.Journal_CustomerDetails.setText(String.format("%s, %s", outletdescr,outletadress));	
				
				if (totalorder_sum>0) {
					holder.Journal_Sum.setVisibility(View.VISIBLE);
					holder.Journal_Sum.setText(String.format("%.2f", totalorder_sum));
				}
				else {
					holder.Journal_Sum.setVisibility(View.INVISIBLE);
				}
				
				
				if (total_sum>0) {
					holder.Journal_AddSum.setVisibility(View.VISIBLE);
					holder.Journal_AddSum.setText(String.format("%.2f", total_sum));
				}
				else {
					holder.Journal_AddSum.setVisibility(View.INVISIBLE);
				}
			
				return convertView;
			
				
			}
			 
			class ViewHolder {			

				ImageView Journal_Status;
				TextView Journal_Date;		
				TextView Journal_Num;
				TextView Journal_CustomerDescr;
				TextView Journal_CustomerDetails;			
				TextView Journal_Sum;
				TextView Journal_AddSum;			
			}
			 
					 
			@Override
			public long getItemId(int position) {

				return 0;
				
			}
			 
			@Override
			public int getCount() {

				return JournalCursor.getCount();
			
			}
			 
			@Override
			public Object getItem(int position) { 
				
				JournalCursor.moveToPosition(position);
				
				id = JournalCursor.getString(0);
				docnum = JournalCursor.getInt(1);
				date_create = JournalCursor.getString(2);
				state = JournalCursor.getInt(3);
				customres_id = JournalCursor.getString(4);
				totalorder_sum = JournalCursor.getDouble(5);
				
				descr = JournalCursor.getString(6);
				outletdescr = JournalCursor.getString(7);
				outletadress = JournalCursor.getString(8);
				
				if (JournalCursor.getColumnCount()>9) {
					total_sum = JournalCursor.getDouble(9);	
				}
				else {
					total_sum = 0.0;
				}
				
				return id;
			
			}
		}
		
}	

